/**
 * 1. 标准巡检整改结果详情页展示
 * 2. 标准巡检整改确认
 */

import Taro, { useRouter } from "@tarojs/taro";
import { PageContainer, RadioGroup, Text, View } from "@tarojs/components";
import { useBoolean, useCreation } from "ahooks";

import ByPopupBottom, {
  ByPopupBottomEvent,
} from "@/components/ui/ByPopupBottom";

import ByTag from "@/components/ui/ByTag";
import ByRow from "@/components/ui/ByRow";
import ByCol from "@/components/ui/ByCol";
import Card from "@/components/common/Card";
import ByCell from "@/components/ui/ByCell";
import Page from "@/components/common/Page";
import ByText from "@/components/ui/ByText";
import ByIcon from "@/components/ui/ByIcon";
import ByRadio from "@/components/ui/ByRadio";
import ByButton from "@/components/ui/ByButton";
import ListView from "@/components/app/ListView";
import Uploader from "@/components/app/Uploader";
import ByCellGroup from "@/components/ui/ByCellGroup";
import FormInput from "@/components/common/FormInput";
import ByImageGroup from "@/components/ui/ByImageGroup";
import PopupContainer from "@/components/app/PopupContainer";

import useAppStore from "@/store";
import useAuth from "@/hooks/useAuth";
import useList from "@/hooks/useList";
import useForm from "@/hooks/useForm";
import useFetch from "@/hooks/useFetch";
import ApiInspection from "@/api/inspection";
import { getTimeDiffFromNow } from "@/utils";


const CellProps = {
  labelWidth: "5em",
  border: true,
} as const;

// 整改确认弹窗
const PopupSubmit = ({
  intentCustomerId,
  rectificationId,
  onCancel,
  onSuccess,
}: {
  rectificationId: number;
  intentCustomerId: number;
  onCancel: () => void;
  onSuccess: () => void;
}) => {
  const { loading, model, setModel, submit } = useForm(
    ApiInspection.rectificationConfirm,
    {
      rules: { feedbackContent: { required: true, message: "请填写整改反馈" } },
      defaultModel: {
        intentCustomerId,
        rectificationId,
        feedbackContent: "",
        pics: [] as string[],
      },
      onSuccess: () => {
        Taro.showToast({ title: "提交成功！" });
        onSuccess();
      },
    }
  );

  return (
    <ByPopupBottom title="整改反馈" onCancel={onCancel}>
      <View className="p-3">
        <ByCell label="反馈描述" vertical requierd>
          <FormInput
            type="textarea"
            placeholder="输入反馈描述"
            value={model.feedbackContent}
            onChange={(e) => setModel({ feedbackContent: e })}
          />
        </ByCell>

        <ByCell label="反馈图片" vertical>
          <ByImageGroup
            showDelete
            urls={model.pics}
            onChange={(res) => setModel({ pics: res })}
            slotFooter={
              <Uploader
                onSuccess={(res) => setModel({ pics: [...model.pics, ...res] })}
              />
            }
          />
        </ByCell>

        <ByButton
          className="mt-6 w-2/3"
          size="large"
          loading={loading}
          onClick={submit}
        >
          提交
        </ByButton>
      </View>
    </ByPopupBottom>
  );
};

// 审核弹窗
const PopupApprove = ({
  intentCustomerId,
  rectificationId,
  onCancel,
  onSuccess,
}: {
  rectificationId: number;
  intentCustomerId: number;
  onCancel: () => void;
  onSuccess: () => void;
}) => {
  const { loading, model, setModel, submit } = useForm(
    ApiInspection.inspectionStandardAudit,
    {
      rules: {
        status: { required: true, message: "请选择审核结论" },
        auditOpinion: { required: true, message: "请填写审核意见" },
      },
      defaultModel: {
        intentCustomerId,
        rectificationId,
        auditOpinion: "",
        // 2 通过 0 不通过
        status: undefined as number | undefined,
        pics: [] as string[],
      },
      onSuccess: () => {
        Taro.showToast({ title: "提交成功！" });
        onSuccess();
      },
    }
  );

  return (
    <ByPopupBottom title="整改审核" onCancel={onCancel}>
      <View className="px-3">
        <ByCell label="审核结论" requierd>
          <RadioGroup
            onChange={(e) => setModel({ status: +e.detail.value[0] })}
          >
            <ByRadio value={2} checked={2 === model.status}>
              通过
            </ByRadio>
            <ByRadio value={0} checked={0 === model.status} className="ml-2">
              驳回
            </ByRadio>
          </RadioGroup>
        </ByCell>

        <ByCell label="审核描述" vertical requierd>
          <FormInput
            type="textarea"
            placeholder="输入审核描述"
            value={model.auditOpinion}
            onChange={(e) => setModel({ auditOpinion: e })}
          />
        </ByCell>

        <ByCell label="审核图片" vertical>
          <ByImageGroup
            showDelete
            urls={model.pics}
            slotFooter={<Uploader onSuccess={res => setModel({ pics: [...model.pics, ...res] })} />} />
        </ByCell>

        <ByButton
          size="large"
          className="mt-6 mb-3 w-2/3"
          type={model.status === 0 ? "error" : "primary"}
          variant={model.status === 0 ? "filled" : "solid"}
          loading={loading}
          onClick={() => submit()}
        >
          {model.status === 0 ? "驳回" : "通过"}
        </ByButton>
      </View>
    </ByPopupBottom>
  );
};

const PopupRecord = ({
  rectificationId,
  onCancel,
}: ByPopupBottomEvent & { rectificationId: number }) => {
  const { loading, list } = useList<{
    id: number;
    createDate: string;
    createUserName: string;
    createUserId: number;
    logType: string;
  }>(ApiInspection.rectificationRecord, {
    defaultParams: [{ rectificationId }],
  });

  return (
    <PopupContainer title="整改操作记录" onCancel={onCancel}>
      <View className="border-t-1 border-line-light mb-3 min-h-[65vh]">
        <ListView loading={loading} isEmpty={list.length === 0}>
          {list.map((item) => (
            <ByRow
              key={item.id}
              className="py-2 px-4 border-b-1 border-line-light"
            >
              <ByCol span={3}>{item.createDate || "-"}</ByCol>
              <ByCol span={"auto"}>{item.createUserName}</ByCol>
              <ByText type="third">{item.logType}</ByText>
            </ByRow>
          ))}
        </ListView>
      </View>
    </PopupContainer>
  );
};

/**
 * 整改反馈详情
 */
type RectificationDetail = {
  status: 0 | 1 | 2 | 3;
  customerName: string;
  decorationFullAddress: string;
  headerId: number
  headerName: string;
  supplyName: string;
  requaireProcessDate: string;
  quesNaireContent: {
    quesName: string;
    quesRemark: string;
    picList?: string[];
  };
  feedbackContent?: string;
  feedbackPics?: string[];
  feedbackUserId?: number;
  feedbackUserName?: string;
  feedbackDate?: string;
  auditUserName?: string;
  auditDate?: string;
  auditOpinion?: string;
  auditPics?: string[];
  auditUserId?: number;
};

const enumStatus = {
  0: { label: "待整改", color: "text-primary" },
  1: { label: "待审核", color: "primary" },
  2: { label: "已通过", color: "success" },
  // 0: { label: "已驳回", color: "error" },
} as const;

export default () => {
  const { params } = useRouter();
  const rectificationId = Number(params.rectificationId);
  const intentCustomerId = Number(params.intentCustomerId);

  const userInfo = useAppStore(state => state.userInfo)

  const getAuth = useAuth();

  // 是否有确认权限
  const canConfirm = getAuth("WeiXinApp_Rectification");
  // 是否有审批权限
  const canAudit = getAuth("WeiXinApp_RectificationAudit");

  console.log("canConfirm", canConfirm, "canAudit", canAudit);

  // 获取整改/反馈内容
  const { data, refresh } = useFetch<RectificationDetail>(
    ApiInspection.rectificationDetail,
    {
      defaultParams: [{ intentCustomerId, rectificationId }],
      showLoading: true,
    }
  );

  // 提交整改反馈/审核
  const [visible, { setTrue, setFalse }] = useBoolean();

  // 展示提交记录弹窗
  const [recordVisible, handlerRecord] = useBoolean();

  // 是否已提交整改结果
  const hadSubmitted = !!data?.feedbackUserId;

  // 审核状态
  const statusTag = enumStatus[data?.status || 0];

  // 是否超时
  const timeout =
    data && !hadSubmitted
      ? getTimeDiffFromNow(data?.requaireProcessDate)
      : undefined;

  const quesContent = useCreation(() => {
    if (data) {
      // 标准 、 日常
      const { quesNaireContent, dailyInspectionDetail } = data;

      if (dailyInspectionDetail) {
        return {
          name: dailyInspectionDetail.type,
          remark: dailyInspectionDetail.remark,
          picList: dailyInspectionDetail.picList?.map((e) => e.picture),
        };
      }

      return {
        name: quesNaireContent.quesName,
        remark: quesNaireContent.quesRemark,
        picList: quesNaireContent.picList,
      };
    }
  }, [data]);


  // 整改人是否是当前登录用户
  const isCurrentUser = userInfo?.user_id === data?.headerId

  return (
    data && (
      <>
        <Page
          footerSticky
          slotFooter={
            <>
              {/* {data.status === 0 && canConfirm && ( */}
              {data.status === 0 && isCurrentUser && (
                <ByButton size="large" className="w-2/3" onClick={setTrue}>
                  提交整改反馈
                </ByButton>
              )}

              {data.status === 1 && canAudit && (
                <ByButton size="large" className="w-2/3" onClick={setTrue}>
                  审核
                </ByButton>
              )}
            </>
          }
        >
          <Card className="m-3">
            <View className="mb-2 font-bold">{data?.customerName}</View>
            <View className="text-sm text-second">
              {data?.decorationFullAddress}
            </View>
          </Card>

          <Card
            title={
              <ByRow content="between">
                <ByText> {quesContent?.name}</ByText>
                <ByIcon
                  className="text-second"
                  size={36}
                  name="Clock"
                  onClick={handlerRecord.setTrue}
                />
              </ByRow>
            }
            className="m-3"

          >
            <ByCell label="责任人" {...CellProps} border={false}>
              {data?.headerName || data?.supplyName}
            </ByCell>

            <ByCell label="要求整改" {...CellProps}>
              {data?.requaireProcessDate}
              {timeout && !!timeout?.day && (
                <ByText type="error" size="sm" className="ml-2">
                  (已延期：{timeout.day}天)
                </ByText>
              )}
            </ByCell>

            <ByCell label="备注" {...CellProps}>
              {quesContent?.remark}
            </ByCell>

            <ByCell label="问题图片" {...CellProps} vertical>
              <ByImageGroup urls={quesContent?.picList} showEmptyTip />
            </ByCell>
          </Card>

          {hadSubmitted && (
            <ByCellGroup
              title="完成整改"
              className="m-3"
              slotRight={
                data.status === 1 && (
                  <ByTag type={statusTag.color} size="small">
                    {statusTag.label}
                  </ByTag>
                )
              }
            >
              <ByCell label="整改人" {...CellProps}>
                <Text className="text-second">{data.feedbackUserName}</Text>
              </ByCell>
              <ByCell label="整改时间" {...CellProps}>
                <Text className="text-second">{data.feedbackDate}</Text>
              </ByCell>
              <ByCell label="描述" {...CellProps}>
                <Text className="text-second">{data.feedbackContent}</Text>
              </ByCell>
              <ByCell label="整改图片" {...CellProps} vertical>
                <ByImageGroup urls={data.feedbackPics} />
              </ByCell>
            </ByCellGroup>
          )}

          {data.status > 1 && (
            <ByCellGroup
              className="m-3"
              title="审批结果"
              slotRight={
                <ByTag type={statusTag.color}>{statusTag.label}</ByTag>
              }
            >
              <ByCell label="审批人" {...CellProps}>
                <Text className="text-second">{data.auditUserName}</Text>
              </ByCell>
              <ByCell label="审批时间" {...CellProps}>
                <Text className="text-second">{data.auditDate}</Text>
              </ByCell>
              <ByCell label="审批描述" {...CellProps}>
                <Text className="text-second">{data.auditOpinion}</Text>
              </ByCell>
              <ByCell label="审批图片" {...CellProps} vertical>
                <ByImageGroup urls={data.auditPics} showEmptyTip />
              </ByCell>
            </ByCellGroup>
          )}
        </Page>

        {visible &&
          (hadSubmitted ? (
            <PopupApprove
              intentCustomerId={intentCustomerId}
              rectificationId={rectificationId}
              onCancel={setFalse}
              onSuccess={() => (setFalse(), refresh())}
            />
          ) : (
            <PopupSubmit
              intentCustomerId={intentCustomerId}
              rectificationId={rectificationId}
              onCancel={setFalse}
              onSuccess={() => (setFalse(), refresh())}
            />
          ))}

        <PageContainer
          round
          show={recordVisible}
          onAfterLeave={handlerRecord.setFalse}
        >
          {recordVisible && (
            <PopupRecord
              rectificationId={rectificationId}
              onCancel={handlerRecord.setFalse}
            />
          )}
        </PageContainer>
      </>
    )
  );
};
